/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.lvyh.lightframe.transaction.core.task;

import com.lvyh.lightframe.transaction.common.constant.TransactionConstant;
import com.lvyh.lightframe.transaction.common.domain.Participant;
import com.lvyh.lightframe.transaction.common.domain.Transaction;
import com.lvyh.lightframe.transaction.common.enums.TransactionEventType;
import com.lvyh.lightframe.transaction.core.event.TransactionEventProducer;
import com.lvyh.lightframe.transaction.core.service.TransactionLogRepositoryService;
import com.lvyh.lightframe.transaction.core.service.TransactionMessageService;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;

/**
 * @author lvyh 2021/06/12.
 */
@Slf4j
public class TransactionRecoverTask implements Runnable {
    private final static Logger logger = LoggerFactory.getLogger(TransactionRecoverTask.class);

    private TransactionEventProducer transactionEventProducer;

    private TransactionMessageService transactionMessageService;

    private TransactionLogRepositoryService transactionLogRepositoryService;

    public TransactionRecoverTask(TransactionMessageService transactionMessageService, TransactionLogRepositoryService transactionLogRepositoryService, TransactionEventProducer transactionEventProducer) {
        this.transactionMessageService = transactionMessageService;
        this.transactionEventProducer = transactionEventProducer;
        this.transactionLogRepositoryService = transactionLogRepositoryService;
    }

    @Override
    public void run() {
        logger.info("[TransactionRecoverTask] transaction recover task running.");
        List<Transaction> transactionList = transactionLogRepositoryService.findRecover(convertDate(), TransactionConstant.RETRIED_COUNT);
        if (!CollectionUtils.isEmpty(transactionList)) {
            for (Transaction transaction : transactionList) {

                log.info("[TransactionRecoverTask] The scheduled task resend the MQ message and attempts to re execute the transaction in error:" + transaction.getTransactionId());
                if (!CollectionUtils.isEmpty(transaction.getParticipants())) {
                    for (Participant participant : transaction.getParticipants()) {
                        transactionMessageService.sendMessage(participant);
                    }
                }

                //Add the number of times an MQ message is sent and publish an update transaction event
                transaction.setSendMessageCount(transaction.getSendMessageCount() + 1);
                transactionEventProducer.publish(transaction, TransactionEventType.UPDATE.getCode());

            }
        }

    }

    private Date convertDate() {
        return new Date(System.currentTimeMillis() - (TransactionConstant.RETRIED_DELAY_TIME * 1000));
    }
}
